package cn.jiyun.service.impl;

import cn.jiyun.mapper.UserMapper;
import cn.jiyun.pojo.User;
import cn.jiyun.service.UserService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public List<User> findAll() {
         String userListStr=redisTemplate.boundValueOps("userList").get();
        ObjectMapper objectMapper = new ObjectMapper();
         List<User>userList = null;
         if (StringUtils.isEmpty(userListStr)){
             userList = userMapper.selectList(null);
             try {
                 String str = objectMapper.writeValueAsString(userList);
                 redisTemplate.boundValueOps("userList").set(str);
             } catch (JsonProcessingException e) {
                 e.printStackTrace();
             }
             System.out.println("数据库查询");
         }else {
             System.out.println("redis查询");
             try {
                 userList = objectMapper.readValue(userListStr,List.class);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return userList;


    }
}





















